//
//  WQ_BaseViewController.swift
//  xinlang
//
//  Created by 联创—王增辉 on 2019/3/18.
//  Copyright © 2019年 lcWorld. All rights reserved.
//

import UIKit

private let CellID = "cellID"

class WQ_BaseViewController: UIViewController {

    var tableView:UITableView?
    var refresh:UIRefreshControl?
    lazy var dataSource = [Any]()
    var isLogin = false
    var visitorInfo:[String:String]?
    var isUpLoad = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.Hex(colorHex: 0x00000f)
        isLogin = (WQ_accessTokenModel.accessTokenModel.access_token != nil)
        addSetUI()
        addNavigation()
        registerNotification()
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
//MARK:- 创建UI
extension WQ_BaseViewController {
    
    //添加登录UI视图
    func addSetUI() {
        isLogin ? setTableViewUI():visitorsUI()
        loadData()
    }
    //添加导航视图
    func addNavigation() {
        let navi = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44 + UIApplication.shared.statusBarFrame.height))
        navi.backgroundColor = UIColor.arcColor
        view.addSubview(navi)
    }
    //添加t列表视图
    func setTableViewUI() {
        tableView = UITableView(frame: UIScreen.main.bounds, style: .plain)
        tableView?.delegate = self
        tableView?.dataSource = self
        
        view.addSubview(tableView!)
        
        refresh = UIRefreshControl.init()
        refresh?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        tableView?.addSubview(refresh!)
        
        tableView?.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: CellID)
        
    }
    //添加未登录视图
    func visitorsUI() {
        let visitor = WQ_visitorsV.init(frame: UIScreen.main.bounds)
        visitor.loginBtn.addTarget(self, action: #selector(loginAction), for: .touchUpInside)
        view.addSubview(visitor)
        visitor.visitor = visitorInfo
    }
    
}
//MARK:- 执行动作
extension WQ_BaseViewController {
    @objc func loginAction() {
        let loginVC = WQ_LoginViewController()
        let naivVC  = UINavigationController(rootViewController: loginVC)
        self.present(naivVC, animated: true, completion: nil)
    }
    @objc func loginChangeAction() {
        view.removeFromSuperview()
        view = nil
        setNeedsFocusUpdate()
    }
}

//MARK:- 数据加载
extension WQ_BaseViewController{
    //加载数据
    @objc func loadData() {
        if isUpLoad {
            DispatchQueue.main.asyncAfter(wallDeadline: DispatchWallTime.now() + 2) {
                for i in (1 ..< 20).reversed() {
                    self.dataSource.append("\(i) ==")
                }
                self.tableView?.reloadData()
                self.isUpLoad = false
            }
        }else{
            DispatchQueue.main.asyncAfter(wallDeadline: DispatchWallTime.now() + 2) {
                for i in 1 ..< 20 {
                    self.dataSource.append("\(i)")
                }
                self.refresh?.endRefreshing()
                self.tableView?.reloadData()
            }
        }
       
    }
}
//MARK:- tableView 代理
extension WQ_BaseViewController:UITableViewDelegate,UITableViewDataSource
{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CellID, for: indexPath)
        let item = dataSource[indexPath.row]
        cell.textLabel?.text = item as? String
        return cell
    }
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let indexSetion = tableView.numberOfSections - 1
        let indexRow    = tableView.numberOfRows(inSection: indexSetion) - 1
        if indexPath.row == indexRow && indexPath.section == indexSetion{
            isUpLoad = true
            loadData()
        }
    }
    
}
//MARK:- 通知相关
extension WQ_BaseViewController{
    func registerNotification() {
        NotificationCenter.default.removeObserver(self)
        NotificationCenter.default.addObserver(self, selector: #selector(loginChangeAction), name: NSNotification.Name.init(loginChangeNotfication), object: nil)
    }
    
}
